package com.typy.www.tpay.ui.acitivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.typy.www.tpay.LoginActivity;
import com.typy.www.tpay.MainActivity;
import com.typy.www.tpay.R;
import com.typy.www.tpay.base.BaseActivity;
import com.typy.www.tpay.bean.bean.BaseReturn;
import com.typy.www.tpay.bean.bean.HomeBtnBean;
import com.typy.www.tpay.bean.listvm.NoticeListVm;
import com.typy.www.tpay.bean.vm.RedMoneyVm;
import com.typy.www.tpay.bean.vm.UserInfoVm;
import com.typy.www.tpay.bean.vm.VersionVm;
import com.typy.www.tpay.constance.Constance;
import com.typy.www.tpay.constance.MessageEvent;
import com.typy.www.tpay.constance.Sharep;
import com.typy.www.tpay.ui.adapter.MineGridAdapter;
import com.typy.www.tpay.ui.dialog.SyDialogHelper;
import com.typy.www.tpay.ui.dialog.SyMessageDialog;
import com.typy.www.tpay.ui.prt.PtrLinearContent;
import com.typy.www.tpay.ui.prt.PtrScrollContent;
import com.typy.www.tpay.ui.view.CircleImageView;
import com.typy.www.tpay.ui.view.LineGridView;
import com.typy.www.tpay.ui.view.StarView;
import com.typy.www.tpay.ui.view.dialog.RedEnvelopeDialog;
import com.typy.www.tpay.util.ClassHoldUtil;
import com.typy.www.tpay.util.GsonUtils;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.MessageAction;
import com.typy.www.tpay.util.ParamsUtil;
import com.typy.www.tpay.util.PopupUtil;
import com.typy.www.tpay.util.PreferencesUtil;
import com.typy.www.tpay.util.StringUtil;
import com.typy.www.tpay.util.ToastUtil;
import com.typy.www.tpay.util.UiHelper;
import com.typy.www.tpay.util.UpdataUiUtil;
import com.typy.www.tpay.util.listviewanimations.IntentUtil;
import com.typy.www.tpay.volley.HTTPUtils;
import com.typy.www.tpay.volley.VolleyListener;
import com.zhy.android.percent.support.PercentLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.ACCESS_NETWORK_STATE;
import static android.Manifest.permission.ACCESS_WIFI_STATE;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.CHANGE_WIFI_STATE;
import static android.Manifest.permission.READ_CALL_LOG;
import static android.Manifest.permission.READ_CONTACTS;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES;
import static android.Manifest.permission.SYSTEM_ALERT_WINDOW;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by 13799 on 2018/6/16.
 */

public class HomeActivity extends BaseActivity {
    public static HomeActivity instance;
    MineGridAdapter adapter;
    UserInfoVm userInfoVm;
    PtrScrollContent ptrLinearContent;
    //    PtrLinearContent ptrLinearContent;
    @BindView(R.id.img_saoyisao)
    ImageView imgSaoyisao;
    @BindView(R.id.ll_amount)
    PercentLinearLayout llAmount;
    @BindView(R.id.ll_share)
    PercentLinearLayout llShare;
    @BindView(R.id.ll_point)
    PercentLinearLayout llPoint;
    @BindView(R.id.stv_xinyu)
    StarView stvXinyu;
    private long exitTime = 0;

    @BindView(R.id.img_userHead)
    CircleImageView imgUserHead;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_userId)
    TextView tvUserId;
    @BindView(R.id.ll_userInfo)
    PercentLinearLayout llUserInfo;
    @BindView(R.id.img_setting)
    ImageView imgSetting;
    @BindView(R.id.tv_yue)
    TextView tvYue;
    @BindView(R.id.tv_fenxiangfen)
    TextView tvFenxiangfen;
    @BindView(R.id.tv_jifen)
    TextView tvJifen;
    @BindView(R.id.gv_mine)
    GridView gvMine;
    List<HomeBtnBean> mHomeList = new ArrayList<>();

    NoticeListVm listVm;
    ArrayList<String> list = new ArrayList<>();
    private RedEnvelopeDialog mRedEnvelopeDialog;


    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private String[] permissions = {WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, CAMERA, ACCESS_FINE_LOCATION,
            ACCESS_COARSE_LOCATION, ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, READ_PHONE_STATE, READ_CONTACTS,
            READ_CALL_LOG, ACCESS_NETWORK_STATE, SYSTEM_ALERT_WINDOW, REQUEST_INSTALL_PACKAGES};
    private ArrayList<String> permissionList = new ArrayList<>();

    public static void show(Context context) {
        IntentUtil.intent2Activity(context, HomeActivity.class);
    }

    @Override
    public int getStatusBarColor() {
        return R.color.home_bg;
    }

    private void checkPermissions() {
        for (int i = 0; i < permissions.length; i++) {
            checkPermission(permissions[i]);
        }
        if (permissionList.size() > 0) {
            String[] permissions = new String[permissionList.size()];
            for (int i = 0; i < permissionList.size(); i++) {
                permissions[i] = permissionList.get(i);
            }
            //申请权限
            ActivityCompat.requestPermissions(this, permissions, REQUEST_WRITE_EXTERNAL_STORAGE);
        }
    }

    private void checkPermission(String permission) {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            permissionList.add(permission);
        }
    }

    @Override
    protected int getTitleBarResId() {
        return -1;
    }


    @Override
    protected View getContentView() {

        ptrLinearContent = new PtrScrollContent(this, R.layout.activity_home2) {
            @Override
            protected void getPage(int pageIndex, boolean refresh) {
                //刷新
                getData(true);
            }
        };
        return ptrLinearContent.getmView();
    }

    @Override
    protected void initView() {
        super.initView();
        instance = this;
        EventBus.getDefault().register(this);
        initAdapter();
        getData(false);
        checkPermissions();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (mRedEnvelopeDialog != null) {
            mRedEnvelopeDialog.dismiss();
            mRedEnvelopeDialog = null;
        }
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(MessageEvent msg) {
        if (msg.getKey().equals(MessageAction.REFRESHUSERINFO)) {
            getData(true);
            getTodayredmoneyData();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private void initAdapter() {
        gvMine = this.findViewById(R.id.gv_mine);
        gvMine.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return MotionEvent.ACTION_MOVE == event.getAction() ? true
                        : false;
            }
        });
        adapter = new MineGridAdapter(this);
        gvMine.setAdapter(adapter);
        gvMine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Object obj = adapterView.getItemAtPosition(i);
                if (obj instanceof HomeBtnBean) {
                    switch (((HomeBtnBean) obj).getBtnName()) {
                        case "激活":
                            ActivicationActivity.show(getActivity(), ClassHoldUtil.Activication);
                            break;
                        case "转出":
                            ActivicationActivity.show(getActivity(), ClassHoldUtil.TurnOut);
//                            TurnOutActivity.show(getActivity());
                            break;
                        case "转入":
                            ChangeIntoActivity.show(getActivity());
                            break;
                        case "兑换积分":
                            ExchangePointActivity.show(getActivity());
                            break;
                        case "买入":
//                            ToastUtil.getInstance().show("敬请期待！");
                            BuyIntoActivity.show(getActivity(), ClassHoldUtil.BUYIN);
                            break;
                        case "卖出":
//                            ToastUtil.getInstance().show("敬请期待！");
                            BuyIntoActivity.show(getActivity(), ClassHoldUtil.SELLOUT);
                            break;
                        case "数字资产":
                            DigitalAssetsActivity.show(getActivity());
                            break;
                        case "分享":
                            ShareActivity.show(getActivity());
                            break;
                        case "商城":
                            ToastUtil.getInstance().show("敬请期待！");
//                            FriendsActivity.show(getActivity());
                            break;
                    }
                }
            }
        });
        setList();
    }


    private void setList() {
        if (mHomeList != null && mHomeList.size() == 0) {
            mHomeList.add(HomeBtnBean.getBean("转出", R.drawable.shouye_zhuanchu));
            mHomeList.add(HomeBtnBean.getBean("转入", R.drawable.shouye_zhuanru));
            mHomeList.add(HomeBtnBean.getBean("激活", R.drawable.shouye_jihuo));
            mHomeList.add(HomeBtnBean.getBean("买入", R.drawable.shouye_mairu));
            mHomeList.add(HomeBtnBean.getBean("卖出", R.drawable.shouye_maichu));
            mHomeList.add(HomeBtnBean.getBean("兑换积分", R.drawable.shouye_duihuanjifen));
            mHomeList.add(HomeBtnBean.getBean("商城", R.drawable.shouye_shangcheng));
            mHomeList.add(HomeBtnBean.getBean("数字资产", R.drawable.shouye_shuzizichan));
            mHomeList.add(HomeBtnBean.getBean("分享", R.drawable.shouye_fenxiang));
        }
        adapter.setList(mHomeList);
        adapter.notifyDataSetChanged();
    }

    //获取个人信息
    private void getData(final boolean refresh) {
        ParamsUtil params = new ParamsUtil();
        HTTPUtils.post(this, Constance.getMyselfinfoURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                userInfoVm = GsonUtils.parseJSON(ret.getData().toString(), UserInfoVm.class);
                updataUserInfo();
                ptrLinearContent.loadInitialPage();
            }

            @Override
            public void onResponseErr(int code, String msg) {
                UiHelper.showToast(getActivity(), msg);
                ptrLinearContent.loadInitialPage();
            }
        });
    }

    //获取今日红包
    private void getTodayredmoneyData() {
        Logutil.print("获取红包");
        ParamsUtil params = new ParamsUtil();
        HTTPUtils.post(this, Constance.getTodayredmoneyURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                RedMoneyVm vm = GsonUtils.parseJSON(ret.getData().toString(), RedMoneyVm.class);
                showRedMoneyDailog(vm);
            }

            @Override
            public void onResponseErr(int code, String msg) {
                ptrLinearContent.loadInitialPage();
            }
        });

    } //保存红包

    private void getSaveredmoneyData(int type) {
        ParamsUtil params = new ParamsUtil();
        params.put("type", type);
        HTTPUtils.post(this, Constance.getSaveredmoneyURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                getData(true);
            }

            @Override
            public void onResponseErr(int code, String msg) {
                getData(true);
                ptrLinearContent.loadInitialPage();
            }
        });
    }

    private void updataUserInfo() {
        if (userInfoVm != null) {
            UpdataUiUtil.getDefaul().setText(userInfoVm.getFdNickName(), tvNickname)
                    .setText("UID " + userInfoVm.getFdId(), tvUserId)
                    .setText(userInfoVm.getFdAmount(), tvYue)
                    .setText(userInfoVm.getFdSharePoint(), tvFenxiangfen)
                    .setText(userInfoVm.getFdPoint(), tvJifen);
            PreferencesUtil.save(Sharep.SHAREURL, userInfoVm.getFdShareUrl());
            PreferencesUtil.save(Sharep.EXCHANGETIP, userInfoVm.getFdExchangeTip());
            UpdataUiUtil.setStart(stvXinyu, 5);
            stvXinyu.setChange(false);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CaptureActivity.SCANNIN_GREQUEST_CODE && resultCode == Activity.RESULT_OK) {

            // 二维码扫描结束
            Bundle bundle = data.getExtras();
            String content = bundle.getString("result");
            if (content.contains(Sharep.TURNOUTQRCODE)) {
                String phone = content.replace(Sharep.TURNOUTQRCODE, "");
                ActivicationSecontActivity.show(getActivity(), "", phone, ClassHoldUtil.TurnOut);
            } else {
                WebActivity.show(getActivity(), "APP下载", content);
            }
        }
    }

    @OnClick({R.id.ll_userInfo, R.id.img_setting, R.id.img_saoyisao, R.id.ll_amount, R.id.ll_share, R.id.ll_point})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_userInfo:
                break;
            case R.id.img_setting:
                SettingActivity.show(this);
                break;
            case R.id.img_saoyisao:
                CaptureActivity.show(getActivity());
                break;

            case R.id.ll_amount:
                RecordActivity.show(getActivity(), ClassHoldUtil.AmountListRecord);
                break;
            case R.id.ll_share:
                RecordActivity.show(getActivity(), ClassHoldUtil.SharePointRecord);
                break;
            case R.id.ll_point:
                RecordActivity.show(getActivity(), ClassHoldUtil.PointRecord);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mRedEnvelopeDialog != null) {
                mRedEnvelopeDialog.dismiss();
                mRedEnvelopeDialog=null;
            }
             if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.show(this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData(true);
        getTodayredmoneyData();
        checkVersion();
    }

    private void showRedMoneyDailog(RedMoneyVm vm) {
        if (vm == null)
            return;
        if (mRedEnvelopeDialog == null) {
            mRedEnvelopeDialog = new RedEnvelopeDialog(getActivity(), R.style.WarningDialog);
        }
        mRedEnvelopeDialog.setListener(new RedEnvelopeDialog.OnDismantlingListener() {
            @Override
            public void onDismantlingRespon(int type) {
                if (mRedEnvelopeDialog != null) {
                    mRedEnvelopeDialog.dismiss();
                }
                //保存红包
                getSaveredmoneyData(type);
            }
        });
        mRedEnvelopeDialog.updataView("", StringUtil.subZeroAndDot(vm.getFdAmount() + "") + "元");
        if (mRedEnvelopeDialog != null && !mRedEnvelopeDialog.isShowing())
            mRedEnvelopeDialog.show();
    }
    private void checkVersion(){
        ParamsUtil params = new ParamsUtil();
        params.put("fdType","android");
        HTTPUtils.post(getActivity(), Constance.getCheckversionURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                if(ret!=null&&ret.getData()!=null){
                    final VersionVm vm=GsonUtils.parseJSON(ret.getData().toString(),VersionVm.class);
                    int version=StringUtil.getLocalVersionCord(getActivity());
                    if(vm.getFdVersion()>(version)){
                        SyDialogHelper.showDlg(getActivity(), "提示", "当前版本不是最新版本，前往更新", "确定", new SyMessageDialog.OnClickListener() {
                            @Override
                            public void onClick(SyMessageDialog dialog) {
                                Uri uri = Uri.parse(vm.getFdDownUrl());
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                            }
                        });
                    }
                }
            }

            @Override
            public void onResponseErr(int code, String msg) {
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
            }
        });
    }

}
